<?php
namespace app\api\controller;

use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Cache;
use app\api\model\UserModel;
use think\Controller;
use think\Request;
use app\conmon\WXBizDataCrypt;
use think\Db;
require_once('SmsTools.php');

class User extends Controller
{
   /**
    * 用户类
    *
    * 我的订单  type = 0:全部  -1:关闭  1:待付款  2:待收货  3:已完成
    */
    public function login(Request $request){
        $goodsid = $request->post();
        UserModel::instance()->login_data($goodsid);

    }
        public function test (){
            ob_start(); //打开缓冲区
            echo "Hellon"; //输出
            header("location:logins");  //把浏览器重定向到index.php
            ob_end_flush();//输出全部内容到浏览器
    }
    public function logins(){
        $content = file_get_contents ( 'php://input' );
        $content=json_decode($content,true);
         $utoken=$content["utoken"];
//         if(!empty($utoken)&&Cache($utoken)){
//             $result["success"]=11;
//             $result['utoken']=$utoken;
//             echo json_encode($result);
//             return;
//         }
        $code=$content["code"];
        $bid = $content["bid"];
        $encryptedData=$content["encryptedData"];
        $iv = $content['iv'];
        /*获取session_key*/

        $s_result=$this->getSession($code,$bid);
        $WxData = new WXBizDataCrypt($s_result['appid'],$s_result['session_key']);
        /*解密用户数据*/
        $errCode = $WxData->decryptData($encryptedData, $iv, $user_data);
       // $wxap_key = md5(uniqid(md5(microtime(true)),true));
        $result=array();
        if($errCode==0){
            $user_data=json_decode($user_data,true);
            $result["success"]=10;
          //  $result['utoken']=$wxap_key;
            $result['openid'] = $s_result['openid'];
            $user_id = $this->wxUserAdd($user_data,$bid);
//            $result['uid'] = $user_id['uid'];
            if($user_id < 1 || empty($user_id)){
                $result["success"]=-1;
                $result['errCode']=0;
                $result['msg']="获取用户信息出错！";
                echo json_encode($result);
                return;
            }
            $user_data['uid']=$user_id;
            //var_dump($user_data['uid']);
            //Cache::set($wxap_key,$user_data,7200);
            echo  json_encode($result);
            return;
        }else{
            $result["success"]=-1;
            $result['errCode']=$errCode;
            $result['msg']="获取用户信息出错！！";
            echo json_encode($result);
            return;
        }
    }

    /*code 换取 session_key*/
    public function getSession($code,$bid) {
        $loginId  = Db::name('business')->where(['bid'=>$bid])->field('appid,secret')->find();

        $s_data['appid'] = $loginId['appid'];
        $s_data['secret'] = $loginId['secret'];
        $s_data['js_code'] = $code;
        $s_data['grant_type']="authorization_code";
        $session_url = 'https://api.weixin.qq.com/sns/jscode2session?'.http_build_query ( $s_data );
        // echo $session_url.'<br/>';
        $content = file_get_contents ( $session_url );
        // echo $content;
        $content = json_decode ( $content, true );
        $content['appid']=$s_data['appid'];
        return $content;
    }
    public function wxUserAdd($data,$bid){

        $t_user = db('user');
        $data1['openid'] = $data['openId'];
        //var_dump($data);
        //echo 1;
        //var_dump($user_info['user_id']);
        if($user_info = $t_user->where('openid',$data1['openid'])->find()){
            $data2['nickname'] = $data['nickName'];
            $data2['head'] = $data['avatarUrl'];
            $insert = $t_user->where('openid',$data1['openid'])->update($data2);
            return $user_info['uid'];
        }
        // if($user_info = $t_user->where('openid',$data1['openid'])->find())
        //echo 1;
        $data1['bid'] = $bid;
        $data1['nickname'] = $data['nickName'];
        $data1['sex'] = $data['gender'];
//        $data1['language'] = $data['language'];
        $data1['address'] = $data['city'];
//        $data1['province'] = $data['province'];
        $data1['head'] = $data['avatarUrl'];
        $data1['regtime'] = time();
        $data1['status'] = 1;
        //$insert_id =
        if($insert_id=$t_user ->insert($data1)){
            return  $insert_id;
        }else{
            return 0;
        }

    }
    public function getUid() {
        $openid = input('param.openid');
//        var_dump($openid);
        if(empty(input('param.openid'))){
            echo json_encode(['data'=>'没有获取权限']);
        }else{
            $loginId  = Db::name('user')->where('openid',$openid)->field('uid,phone,head')->find();
           echo json_encode(['data'=>$loginId['uid'],'phone'=>$loginId['phone'],'head'=>$loginId['head']]);
        }
    }
    /*
     * 小程序上传文件
     */
    public function save(Request $request)
    {
        $file = request()->file('file');
        if($file){
            $info =     $file->move('./public/upload');
            if($info){
                echo 1 ;
            }
        }die;
//        var_dump($file);die;
//          var_dump(json_encode($_FILES));die;
          error_log("FILES:" . json_encode($_FILES) . "\r\n", 3, "./logs/info.log");
//          die;
//        error_log("POST: " . json_encode($_POST) . "\r\n", 3, "./logs/info.log");
//        error_log("city: " . urldecode($_POST["city"]) . "\r\n", 3, "./logs/info.log");
//        error_log("name: " . urldecode($_POST["name"]) . "\r\n", 3, "./logs/info.log");
//        error_log("latitude: " . urldecode($_POST["latitude"]) . "\r\n", 3, "./logs/info.log");
//        error_log("longitude: " . urldecode($_POST["longitude"]) . "\r\n", 3, "./logs/info.log");
//        error_log("restaurant_id: " . urldecode($_POST["restaurant_id"]) . "\r\n", 3, "./logs/info.log");
//        error_log("tags: " . urldecode($_POST["city"]) . "\r\n", 3, "./logs/info.log");
        echo 'success';
    }
    public function reg()
    {
        $arr = input('param.');
        $phone = db('user')->field('phone')->select();

        $arrs = [
            'phone' => $arr['phone'],
            'updatetime' => time()
        ];
        if ($res = db('user')->where('uid',$arr['uid'])->update($arrs)) {
            echo json_encode(['res' => 1,'phone'=>$arr['phone']]);
        }
    }
    public function checkcode (){
        //引入短信验证码
        require_once "SmsSender.php";
        $phone = input('param.phone');
        $phones = db('user')->field('phone')->select();
        $test = 1;
        foreach ($phones as $k=>$v) {
            if( $phone === $v['phone']){
              $test=0;
            }
        }
        if($test == 0){
            echo json_encode(['res'=>0]);
        }
        //实例化
        if($test != 0){
            $sms = controller('Regist', 'controller');
            header("Content-type:text/html;charset=utf-8");
            $code = rand(1000, 9999);

            $str = "您好，你的验证码为code1，请于2分钟内填写。如非本人操作，请忽略本短信。";
            $strs = str_replace('code1', $code, $str);
            //发送
            $sms->reg($phone,$strs);

            if(!empty($phone)){
                echo  $code ;
            }
        }
    }
/**
     * 用户基本信息
     */
    public function userlist(Request $request){
        $uid = $request->get('uid');
        $list = UserModel::instance()->userlist($uid);
        $this->jsonOut($list);
    }
}
